package com.dove.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dove.common.Constants;
import com.dove.common.Result;
import com.dove.controller.Dto.UserDto;
import com.dove.entity.User;
import com.dove.service.IUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Value("$(files.upload.path)")
    private String fileUploadPath;

    @Resource
    private IUserService iUserService;

    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username)&&StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "账号或密码不能为空");
        }
        UserDto login = iUserService.login(userDto);
        return Result.success(login);
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if (StrUtil.isBlank(username)&&StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "账号或密码不能为空");
        }
        Boolean flag = iUserService.register(userDto);
        return Result.success(flag);
    }

    @GetMapping("/username/{username}")
    public Result getByUsername(@PathVariable String username) {
        QueryWrapper<User> qw = new QueryWrapper();
        qw.eq("username",username);
        User user = iUserService.getOne(qw);
        return user!=null?Result.success(user):Result.error("username查询失败");

    }

    @PostMapping
    public Result save(@RequestBody User user) {
        System.out.println("======>"+user.toString());
        boolean b = iUserService.saveOrUpdate(user);
        if (b) {
            return Result.success("保存或更新成功");
        }
        return Result.error("保存或更新失败");
    }

    @DeleteMapping("{id}")
    public Result modify(@PathVariable Integer id) {
        boolean b = iUserService.removeById(id);
        if (b) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        boolean b = iUserService.removeByIds(ids);
        if (b) {
            return Result.success("批量操作成功");
        }
        return Result.error("批量操作失败");
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        boolean b = iUserService.updateById(user);
        if (b) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    @GetMapping
    public Result getAll() {
        List<User> list = iUserService.list();
        return list!=null?Result.success(list):Result.error("查询所有失败");
    }

    @GetMapping("/roles/{role}")
    public Result getUserByRole(@PathVariable String role) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("role", role);
        List<User> userList = iUserService.list(qw);
        return userList!=null?Result.success(userList):Result.error("role查询失败");
    }

    @GetMapping("{id}")
    public Result getById(@PathVariable Integer id) {
        User user = iUserService.getById(id);
        return user!=null?Result.success(user):Result.error("id查询失败");

    }

    @GetMapping("{current}/{size}")
    public Result getPage(@PathVariable Integer current, @PathVariable Integer size, User user) {
        //请求参数和形式参数同名，自动注入，或者直接模型类中的属性和请求参数相同，也会直接注入到模型类中
        IPage<User> page = iUserService.getPage(current, size, user);
        //如果当前页码大于最大页码值，显示第一页
        if (current > page.getPages()) {
            page = iUserService.getPage((int) page.getPages(), size);
        }
        return Result.success(page);
    }

    @GetMapping("/page")
    public Result getPage2(@RequestParam("pageNum") Integer current, @RequestParam("pageSize") Integer size,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String nickname,
                                @RequestParam(defaultValue = "") String address) {
        //请求参数和形式参数同名，自动注入，或者直接模型类中的属性和请求参数相同，也会直接注入到模型类中
/*        IPage<User> page = new Page<>(current, size);
        QueryWrapper<User> qw = new QueryWrapper<>();
        if (!"".equals(username)) {
            qw.like("username", username);
        }
        if (!"".equals(nickname)) {
            qw.like("nickname", nickname);
        }
        if (!"".equals(address)) {
            qw.like("address", address);
        }
        return Result.success(iUserService.page(page, qw));*/
//一对多
        return Result.success(iUserService.myFindPage(new Page<>(current, size), username,nickname,address));
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<User> list = iUserService.list();
        //通过工具类创建writer,输出到对应目录
        //ExcelWriter writer = ExcelUtil.getWriter("d:/writeTest.xlsx");
        //写出到客户端下载（写出到Servlet）
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        //writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatar", "头像");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");

        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    @PostMapping("/import")
    public Result reader(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //通过Bean方式，但、要求表头英文与bean属性对应
        //List<User> list = reader.readAll(User.class);
        //忽略表头
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            user.setAvatar(row.get(6).toString());
            users.add(user);
        }

        boolean b = iUserService.saveBatch(users);
        if (b) {
            return Result.success("导入成功");
        }
        return Result.error("导入失败");
    }
}
